/*
 * @Author: yxfan
 * @Date: 2025-03-01 14:21:48
 * @LastEditTime: 2025-03-01 14:21:55
 * @FilePath: \umi-demo\src\components\hooks\useUpdateState.ts
 * @Description:
 */
import { useRef, useState } from 'react';

/**
 * 类似于 useState，但返回的 setter 函数会返回最新的状态值
 * @param defaultValue 默认值
 * @returns [state, setState]
 */
export default function useUpdateState<T>(
    defaultValue: T,
): [T, (updater: (prev: T) => T) => T] {
    const [value, setValue] = useState<T>(defaultValue);
    const updaterRef = useRef<T>(value);

    const setUpdateValue = (updater: (prev: T) => T) => {
        updaterRef.current = updater(updaterRef.current);
        setValue(updaterRef.current);
        return updaterRef.current;
    };

    return [value, setUpdateValue];
}
